package validators;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.HttpServletRequest;

import DAO.UsuarioDAO;

public class ValidatorEmailUsuarioExistente implements Validator{

	@Override
	public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
		String email = value.toString();
		HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		String emailAtual = request.getParameter("emailatual");		
		
		if(! emailAtual.equals(email))
		{
			if(UsuarioDAO.ExisteUsuarioPorEmail(email))
			{
				((UIInput)component).setValid(false);
				FacesMessage message = new FacesMessage();
				message.setDetail("O RG informado já encontra-se cadastrado!");        
				message.setSeverity(FacesMessage.SEVERITY_ERROR);	        
				throw new ValidatorException(message);
			}				
		}
		
	}

}
